package club.emergency.wechat.persistence.department;

import club.emergency.wechat.model.department.Department;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;


/**
 * <p>
 * Mapper 接口
 * </p>
 *
 * @author jifujun
 * @since 2019-03-20
 */
public interface DepartmentMapper extends BaseMapper<Department> {

    /**
     * parentId为空时候code的最大值，为创建第一级部门之用
     *
     * @return
     */
    @Select("SELECT MAX(`code`) FROM department WHERE ISNULL(`parent_id`) AND using_type = 1")
    String queryParentIdIsNull();

    /**
     * 根据父id和父code查询相邻下一级的code最大值
     *
     * @param parentCode 父code
     * @param parentId   父id
     * @return code最大值
     */
    @Select("SELECT MAX(`code`) FROM department WHERE parent_id = #{parentId} AND using_type = 1 AND code LIKE #{parentCode}")
    String queryMaxCodeWithParentId(@Param("parentCode") String parentCode, @Param("parentId") Long parentId);

    /**
     * 新增时检查企业名称是否重复
     *
     * @param departmentName 企业名称
     * @return 个数
     */
    @Select("SELECT COUNT(`id`) FROM department WHERE department_name = #{departmentName} AND using_type = 1")
    Integer checkOnly(@Param("departmentName") String departmentName);

    /**
     * 检查修改时企业名称名是否唯一
     *
     * @param departmentName 企业名称
     * @param id             自身id
     * @return 个数
     */
    @Select("select count(`id`) from department where department_name = #{departmentName} and id != #{id} AND using_type = 1")
    Integer checkOnlyForEdit(@Param("departmentName") String departmentName, @Param("id") Long id);

    /**
     * 删除时检查是否有子企业
     *
     * @param id 父id
     * @return 子企业个数
     */
    @Select("select count(`id`) from department where parent_id = #{id} and using_type = 1")
    Integer deleteCheckChildren(@Param("id") Long id);
}
